//
//  SendCommentView.swift
//  maopu
//
//  Created by 黄海波 on 2017/4/20.
//  Copyright © 2017年 maopu. All rights reserved.
//

import UIKit

@objc protocol SendCommentViewDelegate {
    @objc optional func sendCommentView( didReturnKey sendCommentView:SendCommentView)
    @objc optional func sendCommentView( chooseImgs sendCommentView:SendCommentView)
}

class SendCommentView: UIView , UITextViewDelegate{
    var hintbottomView:UIView!
    var replyHintBtn:UIButton!
    var shareBtn:UIButton!
    
    var commentlBottomView:UIView!
    var hintLab:UILabel!
    var textView:UITextView!
    var showCheckImgBtn:UIButton!
    var emojiBtn:UIButton!
    
    var toolView:UIView!
    var chooseImagesView:ChooseImagesView!
    var chooseImgCountLab:UILabel!
    
    
    fileprivate var hideKeyBoardView:UIButton!
    fileprivate var isShowToolView:Bool = false
    fileprivate var viewFrame:CGRect!
    fileprivate var imageWidth = Util.shared.getImgWidthForCollectionView(itemSpacing: 0, maxWidth: AppWidth - 20, rowCount: 4)
    
    weak var delegate:SendCommentViewDelegate!
    override init(frame: CGRect){
        super.init(frame: frame)
        self.viewFrame = frame
        self.initializeView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.initializeView()
    }
    
    fileprivate func initializeView() -> Void{
        if self.viewFrame == nil{
            self.viewFrame = CGRect.init(x: 0, y: AppHeight - 50, width: AppWidth, height: 50)
        }
        
        self.hideKeyBoardView = UIButton.init(type: .custom)
        self.hideKeyBoardView.backgroundColor = UIColor.clear
        self.hideKeyBoardView.addTarget(self, action: #selector(self.hideKeyBoardClick), for: .touchUpInside)
        
        self.hintbottomView = UIView()
        self.hintbottomView.frame = CGRect.init(x: 0, y: 0, width: AppWidth, height: 50)
        self.hintbottomView.backgroundColor = UIColor.white
        self.addSubview(self.hintbottomView)
//        self.hintbottomView.snp.makeConstraints { (make) in
//            make.left.top.right.equalTo(self)
//            make.height.equalTo(50)
//        }
        
        let lineView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: AppWidth, height: 1))
        lineView.backgroundColor = UIColor.m_lineColor()
        self.addSubview(lineView)
        
        self.replyHintBtn = UIButton.init(type: .custom)
        self.replyHintBtn.frame = CGRect.init(x: 15, y: 10, width: AppWidth - 65, height: 30)
        self.replyHintBtn.titleLabel?.font = UIFont.LightDefaultFont(15)
        self.replyHintBtn.setTitleColor(UIColor.m_textLightColor(), for: UIControlState())
        self.replyHintBtn.backgroundColor = UIColor.m_viewBackgroundColor()
        self.replyHintBtn.setTitle("  回个帖帮楼主推荐", for: UIControlState())
        self.replyHintBtn.contentHorizontalAlignment = .left
        self.replyHintBtn.addTarget(self, action: #selector(self.showCommentToolView), for: UIControlEvents.touchUpInside)
        self.hintbottomView.addSubview(self.replyHintBtn)
        
        self.shareBtn = UIButton.init(type: .custom)
        self.shareBtn.addTarget(self, action: #selector(self.chooseImagesClick), for: .touchUpInside)
        self.shareBtn.frame = CGRect.init(x: AppWidth - 50 , y: 0, width: 50, height: 50)
        self.shareBtn.setImage(UIImage.init(named: "tool_share"), for: UIControlState())
        self.shareBtn.imageView?.contentMode = .scaleToFill
        self.hintbottomView.addSubview(self.shareBtn)
        
        self.commentlBottomView = UIView()
        self.commentlBottomView.frame = CGRect.init(x: 0, y: 0, width: AppWidth, height: 50)
        self.commentlBottomView.isHidden = true
        self.commentlBottomView.backgroundColor = UIColor.white
        self.addSubview(self.commentlBottomView)
        
        let lineView_one = UIView.init(frame: CGRect.init(x: 0, y: 0, width: AppWidth, height: 1))
        lineView_one.backgroundColor = UIColor.m_lineColor()
        self.commentlBottomView.addSubview(lineView_one)
        
        let lineView_two = UIView.init(frame: CGRect.init(x: 0, y: self.commentlBottomView.frame.maxY, width: AppWidth, height: 1))
        lineView_two.backgroundColor = UIColor.m_lineColor()
        self.commentlBottomView.addSubview(lineView_two)
        lineView_two.snp.makeConstraints { (make) in
            make.left.right.width.equalTo(self.commentlBottomView)
            make.height.equalTo(1)
            make.bottom.equalTo(self.commentlBottomView)
        }
        
        self.textView = UITextView.init(frame: CGRect.init(x: 80, y: 10, width: AppWidth - 90, height: 30))
        self.textView.backgroundColor = UIColor.m_viewBackgroundColor()
        self.textView.font = UIFont.LightDefaultFont(15)
        self.textView.textColor = UIColor.m_textDeepColor()
        self.textView.contentInset = UIEdgeInsets.init(top: -3, left: 2, bottom: 0, right: 0)
        self.textView.contentMode = .topLeft
        self.textView.delegate = self
        self.textView.returnKeyType = .send
        self.textView.text = ""
        self.commentlBottomView.addSubview(self.textView)
        
        self.showCheckImgBtn = UIButton.init(type: .custom)
        self.showCheckImgBtn.frame = CGRect.init(x: 0 , y: 5, width: 40, height: 40)
        self.showCheckImgBtn.isEnabled = true
        self.showCheckImgBtn.addTarget(self, action: #selector(self.chooseImagesClick), for: .touchUpInside)
        self.showCheckImgBtn.setImage(UIImage.init(named: "showTool_ico"), for: UIControlState())
        self.showCheckImgBtn.setImage(UIImage.init(named: "showTool_hl_ico"), for: .selected)
        self.showCheckImgBtn.imageView?.contentMode = .scaleToFill
        self.commentlBottomView.addSubview(self.showCheckImgBtn)
        
        self.emojiBtn = UIButton.init(type: .custom)
        self.emojiBtn.addTarget(self, action: #selector(self.chooseImagesClick), for: .touchUpInside)
        self.emojiBtn.frame = CGRect.init(x: 40 , y: 5, width: 40, height: 40)
        self.emojiBtn.setImage(UIImage.init(named: "chooseEmoji_ico"), for: UIControlState())
        self.emojiBtn.imageView?.contentMode = .scaleToFill
        self.commentlBottomView.addSubview(self.emojiBtn)
        
        self.hintLab = UILabel.init(frame: CGRect.init(x: 5, y: 10, width: 200, height: 16))
        self.hintLab.font = UIFont.LightDefaultFont(15)
        self.hintLab.textColor = UIColor.m_textLightColor()
        self.hintLab.text = " 除了666，再说点别的吧"
        self.textView.addSubview(self.hintLab)
        
        self.toolView = UIView.init(frame: CGRect.init(x: 0, y: self.commentlBottomView.frame.maxY, width: AppWidth, height: 0))
        self.toolView.backgroundColor = UIColor.white
        self.toolView.layer.masksToBounds = true
        self.addSubview(self.toolView)
        
        self.chooseImgCountLab = UILabel()
        self.chooseImgCountLab.frame = CGRect.init(x: 0, y: 0, width: AppWidth, height: 00)
        self.chooseImgCountLab.text = "已添加 6/9"
        self.chooseImgCountLab.font = UIFont.RegularDefaultFont(12)
        self.chooseImgCountLab.textColor = UIColor.m_textGrayColor()
        self.chooseImgCountLab.textAlignment = .center
        self.chooseImgCountLab.backgroundColor = UIColor.clear
        self.toolView.addSubview(self.chooseImgCountLab)

        self.chooseImagesView = ChooseImagesView.init(scrollDirection: .horizontal, frame: CGRect.init(x: 0, y: 20 , width: AppWidth, height: 0) , cellWidth: imageWidth)
        self.chooseImagesView.backgroundColor = UIColor.white
        self.toolView.addSubview(self.chooseImagesView)
        self.chooseImagesView.layoutIfNeeded()
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(self.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
        
        self.commentlBottomView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.height.equalTo(50)
        }
        
        self.layoutIfNeeded()
    }
    
    func textViewDidChange(_ textView: UITextView) {
        if(self.textView.text.characters.count > 0){
            self.hintLab.isHidden = true
        }else{
            self.hintLab.isHidden = false
        }
        let textHeight = StringSizeEngine.calculateStringHeight(self.textView.text, width: self.textView.frame.size.width, font: self.textView.font!)
        var height:CGFloat = 0
        if textHeight > 85{
            height = 85 + 6
        }else{
            height = textHeight + 6
        }
        if height < 30{
            height = 30
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n"{
            if self.delegate != nil{
                self.delegate.sendCommentView!(didReturnKey: self)
            }
            return false
        }
        return true
    }
    
    func chooseImagesClick() -> Void {
        self.isShowToolView = true
        self.textView.resignFirstResponder()
        UIView.animate(withDuration: 0.4) {
            self.frame = CGRect.init(x: 0, y: AppHeight - 220 , width: AppWidth, height: 220)
            self.toolView.frame = CGRect.init(x: 0, y: 50 , width: AppWidth, height: 170)
            self.chooseImgCountLab.frame = CGRect.init(x: 0, y: 20 + self.imageWidth + 10 , width: AppWidth, height: self.toolView.frame.size.height - 30 - self.imageWidth)
            
            self.hideKeyBoardView.frame = CGRect.init(x: 0, y: 0, width: AppWidth, height: AppHeight - self.frame.size.height)
            self.toolView.layoutIfNeeded()
            self.layoutIfNeeded()
        }
    }
    
    func keyBoardWillShow(_ note:Notification){
        self.isShowToolView = false
        self.bringSubview(toFront: self.commentlBottomView)
        
        self.superview!.addSubview(self.hideKeyBoardView)
        self.commentlBottomView.isHidden = false
        self.hintbottomView.isHidden = false
        
        let userInfo:NSDictionary  = (note as NSNotification).userInfo! as NSDictionary
        let  keyBoardBounds = (userInfo[UIKeyboardFrameEndUserInfoKey]as! NSValue).cgRectValue
        let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let deltaY = keyBoardBounds.size.height
        
        let animations:(() -> Void) = {
            self.frame = CGRect.init(x: 0, y: AppHeight - deltaY - self.commentlBottomView.frame.height , width: AppWidth, height: deltaY + self.commentlBottomView.frame.size.height)
            self.toolView.frame = CGRect.init(x: 0, y: 0 , width: AppWidth, height: deltaY + 50)
        }
        
        self.hideKeyBoardView.frame = CGRect.init(x: 0, y: 0, width: AppWidth, height: AppHeight - deltaY - self.commentlBottomView.frame.height)
        
        if duration > 0 {
            let options = UIViewAnimationOptions(rawValue: UInt((userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
            UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
        }else{
            animations()
        }
    }
    
    func keyBoardWillHide(_ note:Notification){
        if isShowToolView{
            return
        }
        
        if hideKeyBoardView.superview != nil{
            self.hideKeyBoardView.removeFromSuperview()
        }
        self.sendSubview(toBack: self.commentlBottomView)
        self.commentlBottomView.isHidden = true
        self.hintbottomView.isHidden = false
        
        let userInfo  = (note as NSNotification).userInfo
        let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let animations:(() -> Void) = {
            self.frame = self.viewFrame
            self.toolView.frame = CGRect.init(x: 0, y: 0 , width: AppWidth, height: 0)
        }
        self.isShowToolView = false
        
        if duration > 0 {
            let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
            UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
        }else{
            animations()
        }
    }
    
    @objc func showToolViewClick(){
        if self.textView != nil{
            self.textView.resignFirstResponder()
        }
    }
    
    @objc func hideKeyBoardClick(){
        self.isShowToolView = false
        if self.textView.isFirstResponder{
            if self.textView != nil{
                self.textView.resignFirstResponder()
            }
        }else{
            self.commentlBottomView.isHidden = true
            self.hintbottomView.isHidden = false
            UIView.animate(withDuration: 0.4, animations: {
                self.frame = self.viewFrame
                
                self.toolView.frame = CGRect.init(x: 0, y: 0 , width: AppWidth, height: 0)
            })
        }
    }
    
    @objc func showCommentToolView(){
        if self.textView != nil{
            self.textView.becomeFirstResponder()
        }
    }
}



